package LMR.rbac.service;

import LMR.rbac.Entity.Dept;
import LMR.rbac.dto.Deptdto;
import LMR.rbac.vo.DeptVo;
import LMR.rbac.vo.Result;
import java.util.Arrays;

public class Deptservice {
    public static int Data_Size=100;
    public static Dept[] data=new Dept[Data_Size+1];
    public static int idCounter=1;
    public static DeptVo convertToVo(Dept dept){
        return new DeptVo(dept.id, dept.name, dept.phone);
    }
    public static Dept createEntity(Deptdto dto,int id){
        Dept dept=new Dept(dto.name,dto.phone);
        dept.id=id;
        return dept;
    }
    public static void updateEntity(Dept dept,Deptdto dto){
        dept.name=dto.name;
        dept.phone=dto.phone;
    }
    public static  boolean existsById(int id){
        return id>=1&&id<idCounter&&data[id]!=null;
    }
    public static Dept findById(int id){
        if (existsById(id)){
            return data[id];
        }
        return null;
    }
    public static Result list(){
        DeptVo[] temp=new DeptVo[Data_Size];
        int length=0;
        for (int i=1;i<idCounter;i++){
            if (data[i]!=null){
                temp[length++]=convertToVo(data[i]);
            }
        }
        return Result.success("查询成功", Arrays.copyOf(temp,length));
    }
    public static Result create(Deptdto dto){
        if (idCounter>Data_Size){
            return Result.failure("创建失败，数据已满");
        }
        Dept dept=createEntity(dto,idCounter++);
        data[dept.id]=dept;
        return Result.success("创建成功",null);
    }
    public  static Result update(Deptdto dto,int id){
        if (!existsById(id)){
            return Result.failure("更新失败，id不存在");
        }
        updateEntity(data[id],dto);
        return Result.success("更新成功",null);
    }
    public static Result delete(int id){
        if (existsById(id)){
            return Result.failure("没有该ID对应的数据");
        }
        if (Userservice.deptInUse(id)){
            return Result.failure("该部门存在用户，不能删除");
        }
        data[id]=null;
        return Result.success("删除成功",null);
    }
}
